package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author 东哥
 * @since 2024-08-26
 */
//@Service
@RequiredArgsConstructor
public class LikedRecordServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {
    private final RabbitMqHelper mqHelper;

    /**
     * 1、点赞或者取消点赞 （Day6 - 随堂1）
     *
     * @param recordFormDTO
     */
    @Override
    public void likeOrUnLike(LikeRecordFormDTO recordFormDTO) {
        // 1、基于前端参数，判断点赞还是取消点赞，根据判断结果，执行点赞、取消点赞，返回是否成功
        boolean isSuccess = recordFormDTO.getLiked() ? like(recordFormDTO) : unLike(recordFormDTO);

        // 2、判断是否执行成功，如果失败，直接结束
        if(!isSuccess){
            return;
        }

        // 3、如果执行成功，统计点赞数
        Integer likeTimes = lambdaQuery().eq(LikedRecord::getBizId, recordFormDTO.getBizId()).count();

        // 4、发送MQ消息，通知业务方修改点赞数
        mqHelper.send(LIKE_RECORD_EXCHANGE,
                StringUtils.format(LIKED_TIMES_KEY_TEMPLATE,recordFormDTO.getBizType()),
                LikedTimesDTO.of(recordFormDTO.getBizId(),likeTimes));
    }

    /**
     * 2、根据业务ID集合查询点赞状态（Day6 - 随堂2）
     *
     * @param bizIds 待检测业务ID集合
     * @return 已点赞的业务ID集合
     */
    @Override
    public Set<Long> isLiked(List<Long> bizIds) {
        // 1、查询点赞记录
        List<LikedRecord> list = lambdaQuery()
                .select(LikedRecord::getBizId)
                .eq(LikedRecord::getUserId, UserContext.getUser())
                .in(LikedRecord::getBizId, bizIds)
                .list();

        // 2、返回已经点赞的业务ID集合
        return list.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());
    }

    /**
     * 3、定时读取zset中的点赞数并发送消息至业务方 - 更新点赞数（Day6 -随堂3）
     *
     * @param bizType
     * @param maxBizSize
     */
    @Override
    public void readLikedTimesAndSendMessage(String bizType, Integer maxBizSize) {

    }

    /**
     * 取消点赞
     * @param recordFormDTO
     * @return
     */
    private boolean unLike(LikeRecordFormDTO recordFormDTO) {
        /*Wrappers.<LikedRecord>lambdaQuery()
                .eq(LikedRecord::getBizId, recordFormDTO.getBizId())
                .eq(LikedRecord::getUserId, UserContext.getUser());*/
        return remove(new LambdaQueryWrapper<LikedRecord>()
                .eq(LikedRecord::getBizId, recordFormDTO.getBizId())
                .eq(LikedRecord::getUserId, UserContext.getUser()));
    }

    /**
     * 点赞
     * @param recordFormDTO
     * @return
     */
    private boolean like(LikeRecordFormDTO recordFormDTO) {
        // 1、查询点赞记录
        Integer count = this.lambdaQuery()
                .eq(LikedRecord::getBizId, recordFormDTO.getBizId())
                .eq(LikedRecord::getUserId, UserContext.getUser())
                .count();

        // 2、判断是否存在，如果已经存在，直接返回false
        if(count > 0) return false;

        // 3、如果不存在，新增点赞记录
        // @Accessors(chain = true)
        LikedRecord likedRecord = new LikedRecord()
                .setUserId(UserContext.getUser())
                .setBizType(recordFormDTO.getBizType())
                .setBizId(recordFormDTO.getBizId());

        // @Builder
       /* LikedRecord likedRecord = LikedRecord.builder()
                .userId(UserContext.getUser())
                .bizType(recordFormDTO.getBizType())
                .bizId(recordFormDTO.getBizId())
                .build();*/
        return save(likedRecord);
    }
}
